<?php
namespace app\model;

use Illuminate\Database\Eloquent\Model;

class AccountingRecord extends Model
{
    protected $table = 'accounting_records';
    
    const TYPE_SCORE = 'score';
    const TYPE_TEA_MEAL = 'tea_meal';
    
    protected $fillable = [
        'room_id',
        'user_id',
        'target_user_id',
        'score',
        'description',
        'type',
        'is_settled'
    ];

    protected $casts = [
        'room_id' => 'integer',
        'user_id' => 'integer',
        'target_user_id' => 'integer',
        'score' => 'integer',
        'is_settled' => 'boolean',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * 关联房间
     */
    public function room()
    {
        return $this->belongsTo(Room::class, 'room_id');
    }

    /**
     * 关联用户
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * 关联目标用户
     */
    public function targetUser()
    {
        return $this->belongsTo(User::class, 'target_user_id');
    }

    /**
     * 创建记账记录
     */
    public static function createRecord($data)
    {
        try {
            // 验证必需字段
            $requiredFields = ['room_id', 'user_id', 'target_user_id', 'score'];
            foreach ($requiredFields as $field) {
                if (!isset($data[$field])) {
                    throw new \Exception("缺少必需字段: {$field}");
                }
            }

            // 创建记录实例
            $record = new static();
            
            // 设置字段值，确保数据类型正确
            $record->room_id = (int)$data['room_id'];
            $record->user_id = (int)$data['user_id'];
            $record->target_user_id = (int)$data['target_user_id'];
            $record->score = (int)$data['score'];
            $record->description = $data['description'] ?? '';
            $record->type = $data['type'] ?? static::TYPE_SCORE;
            $record->is_settled = $data['is_settled'] ?? 0;
            
            // 记录调试信息
            error_log('AccountingRecord::createRecord - 准备保存记录: ' . json_encode($record->toArray()));
            
            // 保存记录
            $result = $record->save();
            
            if (!$result) {
                throw new \Exception('保存记录失败');
            }
            
            error_log('AccountingRecord::createRecord - 记录保存成功，ID: ' . $record->id);
            
            return $record;
        } catch (\Exception $e) {
            error_log('AccountingRecord::createRecord - 错误: ' . $e->getMessage());
            error_log('AccountingRecord::createRecord - 数据: ' . json_encode($data));
            throw $e;
        }
    }
}
